#include "head.hpp"

int main()
{
    key_t key = ftok(PATH_NAME, ID);
    if (key == -1)
    {
        perror("ftok");
        exit(1);
    }
    log("ftok key success", Debug) << "key: " << key << endl;

    // 链接共享内存
    int shmid = shmget(key, SIZE, IPC_CREAT);
    if (shmid == -1)
    {
        perror("shmid");
        exit(2);
    }
    log("shmget success", Debug) << "shmid: " << shmid << endl;
    // sleep(10);

    // 挂接shm
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    if (shmaddr == (char *)-1)
    {
        perror("shmat");
        exit(3);
    }
    log("shmat success", Debug) << "shmaddr: " << (void *)shmaddr << endl;
    // sleep(10);
    // 进行写操作
    int fifo_fd = Open(FIFO_NAME, WRITE);
    while(true)
    {
        ssize_t sz = read(0, shmaddr, SIZE - 1);
        assert(sz > 0);
        shmaddr[sz - 1] = '\0';
        Signal(fifo_fd);
        if(strcmp("quit", shmaddr) == 0)
            break;
    }


    // while (true)
    // {
    //     ssize_t sz = read(0, shmaddr, SIZE - 1);
    //     assert(sz > 0);
    //     shmaddr[sz - 1] = '\0';
    //     if(strcmp("quit", shmaddr) == 0)
    //         break;
    // }
    // char a = 'a';
    // for(; a <= 'z'; a++)
    // {
    //     shmaddr[a - 'a'] = a;
    //     //snprintf(shmaddr, SIZE, "我是client,我的pid:%d,信息:%c", getpid(), a);
    //     sleep(1);
    // }
    // strcpy(shmaddr, "quit");
    log("client quit", Notice) << endl;

    // 分离挂接
    int ret = shmdt(shmaddr);
    assert(ret != -1);
    log("shmdt success", Debug) << "shmaddr: " << (void *)shmaddr << endl;
    // 不需要删除
    return 0;
}